﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;

namespace BlazorTable.Pages
{
    public class Food
    {
        [Required]
        public string Name { get; set; }

        [Required]
        public int Age { get; set; }
    }
    public partial class TableDemo
    {

        private Food Model { get; set; }
        [NotNull]
        private List<Food>? Items { get; set; } = new List<Food>();
        /// <summary>
        /// ToastService 服务实例
        /// </summary>
        [Inject]
        [NotNull]
        public ToastService? Toast { get; set; }

        /// <summary>
        ///
        /// </summary>
        protected override void OnInitialized()
        {
            base.OnInitialized();

            Model = new Food() { Name = "张三", Age = 20 };
            Items.Add(Model);
        }

        private Task<bool> OnSaveAsync(Food item, ItemChangedType changedType)
        {
            return Task.FromResult(true);
        }

        private Task<bool> OnDeleteAsync(IEnumerable<Food> items)
        {
            items.ToList().ForEach(i => Items.Remove(i));
            return Task.FromResult(true);
        }

        private Task<QueryData<Food>> OnQueryAsync(QueryPageOptions options)
        {
            IEnumerable<Food> items = Items;

            // 过滤
            var isFiltered = false;
            if (options.Filters.Any())
            {
                items = items.Where(options.Filters.GetFilterFunc<Food>());
                isFiltered = true;
            }

            // 排序
            var isSorted = false;

            // 设置记录总数
            var total = items.Count();

            // 内存分页
            items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();

            return Task.FromResult(new QueryData<Food>()
            {
                Items = items,
                TotalCount = total,
                IsSorted = isSorted,
                IsFiltered = isFiltered,
                IsSearch = true
            });
        }
        /// <summary>
        /// 回车扫描
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        protected Task OnEnterAsync(string val)
        {
            ShowToast($"获取内容:{val}");
            return Task.CompletedTask;
        }
        /// <summary>
        /// 弹出消息
        /// </summary>
        /// <param name="Content"></param>
        /// <param name="isSuccess"></param>
        protected Task ShowToast(string Content)
        {
            var option = new ToastOption
            {
                Category = ToastCategory.Success,
                Title = "温馨提示"
            };
            option.Content = $"{Content}";
            return Toast.Show(option);
        }
    }
}
